package rhelper

import (
	"fmt"
	"strconv"
	"strings"
)

func CommaString2Array(src string) []string {
	if src == "" {
		return []string{}
	}

	var result []string
	if strings.Contains(src, ",") {
		result = strings.Split(src, ",")
	} else {
		result = []string{src}
	}

	return result
}

func SplitString2Array(src string, splitchar string) []string {
	if src == "" {
		return []string{}
	}

	var result []string
	if strings.Contains(src, splitchar) {
		result = strings.Split(src, splitchar)
	} else {
		result = []string{src}
	}

	return result
}

func CommaStringContain(src string, substr string) bool {
	result := CommaString2Array(src)
	for _, a := range result {
		if a == substr {
			return true
		}
	}
	return false
}

func CommaStringAppend(src string, appendx string) string {
	if src == "" {
		return appendx
	}

	if CommaStringContain(src, appendx) {
		return src
	}

	return src + "," + appendx
}

func CommaReportAppend(src string, currentTime string, e string, t string) string {
	inte, err := strconv.ParseUint(e, 16, 32)
	if err != nil {
		panic(err)
	}

	intt, err := strconv.ParseUint(t, 16, 32)
	if err != nil {
		panic(err)
	}

	if src == "" {
		return fmt.Sprintf("%s:%d:%d", currentTime, inte, intt)
	}

	s := strings.Split(src, ":")
	lastTime := s[0]

	if currentTime != lastTime {
		return fmt.Sprintf("%s:%d:%d", currentTime, inte, intt)
	}

	stre := s[1]
	strt := s[2]

	srce, _ := strconv.ParseUint(stre, 10, 32)
	inte = inte + srce

	srct, _ := strconv.ParseUint(strt, 10, 32)
	intt = intt + srct

	return fmt.Sprintf("%s:%d:%d", currentTime, inte, intt)

}

func CommaStringDelete(src string, appendx string) string {
	if src == "" {
		return ""
	}

	strArray := CommaString2Array(src)
	for index, element := range strArray {
		if element == appendx {
			strArray = append(strArray[:index], strArray[index+1:]...)
			break
		}
	}

	str := ""
	for _, element := range strArray {
		str = str + element + ","
	}

	strSize := len(str)
	if strSize > 0 && str[strSize-1] == ',' {
		str = str[:strSize-1]
	}
	return str
}
